package com.rockxin.cat.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatSpinner;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.rockxin.cat.R;
import com.rockxin.cat.adapter.SpinnerAdapter;
import com.rockxin.cat.base.BaseActivity;
import com.rockxin.cat.base.User;
import com.rockxin.cat.network.CatNetWork;
import com.rockxin.cat.network.HttpResult;
import com.rockxin.cat.utils.GlideCircleTransform;
import com.rockxin.cat.utils.ToastUtils;
import com.rockxin.cat.utils.imageUtils.IGetImageListener;
import com.rockxin.cat.utils.imageUtils.ImageUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.qqtheme.framework.intefaces.IGetAddressPicker;
import cn.qqtheme.framework.picker.AddressPicker;
import cn.qqtheme.framework.task.AddressInitTask;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Subscriber;

import static butterknife.internal.Utils.arrayOf;

public class PersonalDataActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    @BindView(R.id.back_img)
    ImageView backImg;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.idNum)
    TextView idNum;
    @BindView(R.id.nickName)
    TextView nickName;
    @BindView(R.id.spinner)
    AppCompatSpinner spinner;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.commit)
    TextView commit;
    @BindView(R.id.headView)
    CircleImageView headView;
    private static final int REQUEST_CODE_CHOOSE_HEAD = 0x11;

    private PersonalDataActivity mPersonalDataActivity;
    private static final int RC_CAMERA_AND_STORAGE = 0x123;
    private String provinceId;
    private String cityId;
    private int sexId;      // 0:男，1：女
    private SpinnerAdapter adapter;
    private CatNetWork catNetWork;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_personal_data;
    }

    @Override
    public void initData() {
        mPersonalDataActivity = this;
        title.setText("个人资料");

        if (catNetWork == null) {
            catNetWork = new CatNetWork();
        }

        adapter = new SpinnerAdapter(Arrays.asList(getResources().getStringArray(R.array.spinnerSex)));
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sexId = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        Glide.with(mPersonalDataActivity)
                .load(User.getInstance().getUserInfo().getAvatar())
                .error(R.mipmap.image_cats)
                .transform(new GlideCircleTransform(mPersonalDataActivity))
                .into(headView);
        idNum.setText("yx" + User.getInstance().getUserInfo().getMobile());
        nickName.setText(User.getInstance().getUserInfo().getUser_name());
        if (User.getInstance().getUserInfo().getSex().equals("0")) {
            spinner.setSelection(0);
        } else {
            spinner.setSelection(1);
        }

        address.setText(User.getInstance().getUserInfo().getProvince()+" "+User.getInstance().getUserInfo().getCity());

    }

    @OnClick({R.id.back_img, R.id.commit, R.id.headView, R.id.address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_img:
                finish();
                break;
            case R.id.commit:
                catNetWork = new CatNetWork();
                HashMap<String, String> stringHashMap = new HashMap<>();
                stringHashMap.put("token", User.getInstance().getToken());
                stringHashMap.put("province_id", provinceId);
                stringHashMap.put("city_id", cityId);
                stringHashMap.put("sex", String.valueOf(sexId));
                catNetWork.editPersonal(stringHashMap, new Subscriber<HttpResult>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(HttpResult httpResult) {
                        ToastUtils.showLongToast(httpResult.getInfo());
                    }
                });
                break;
            case R.id.headView:
                methodRequiresTwoPermission();
                break;
            case R.id.address:
                new AddressInitTask(mPersonalDataActivity, new IGetAddressPicker() {
                    @Override
                    public void getAddress(AddressPicker.Province province, AddressPicker.City city, AddressPicker.County county) {
                        provinceId = province.getAreaId();
                        cityId = city.getAreaId();
                        String _province = province.getAreaName();
                        String _city = city.getAreaName();
                        String _county = county.getAreaName();
                        if (province.getAreaName().equals(city.getAreaName())) {
                            address.setText(_city + "  " + _county);
                        } else {
                            address.setText(_province + " " + _city + " ");
                        }
                    }
                }).execute("北京", "北京", "东城区");


                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                final List<Uri> uris = Matisse.obtainResult(data);
                Glide.with(mPersonalDataActivity)
                        .load(uris.get(0))
                        .into(headView);

                Logger.e("--------->" + uris.get(0));

                final String realFilePath = getRealPathFromURI(mPersonalDataActivity, uris.get(0));
                Logger.e(realFilePath);

                compressLogo(realFilePath);

            }
        }
    }

    @AfterPermissionGranted(RC_CAMERA_AND_STORAGE)
    private void methodRequiresTwoPermission() {
        final String[] perms = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (EasyPermissions.hasPermissions(this, perms)) {
            Matisse.from(mPersonalDataActivity)
                    .choose(MimeType.allOf())
                    .countable(true)
                    .maxSelectable(1)
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine())
                    .forResult(REQUEST_CODE_CHOOSE_HEAD);
        } else {
            EasyPermissions.requestPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    RC_CAMERA_AND_STORAGE, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Matisse.from(mPersonalDataActivity)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(REQUEST_CODE_CHOOSE_HEAD);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        methodRequiresTwoPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 壓縮入駐圖片
     *
     * @param picturePath
     */
    private void compressLogo(String picturePath) {
        //壓縮
        ImageUtils.getThumbImage(picturePath, new IGetImageListener() {
            @Override
            public void loadSuccess(String[] path) {
                File file = new File(path[0]);

                RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("token", User.getInstance().getToken())
                        .addFormDataPart("data", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                        .build();
                catNetWork.upImg(requestBody, new Subscriber<HttpResult>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(HttpResult HttpResult) {
                        if (HttpResult.getStatus() == 1) {
                            ToastUtils.showShortToastSafe(HttpResult.getInfo());
                        }
                    }
                });

            }

            @Override
            public void loadError(String[] path) {
                Logger.e("error" + path[0]);
            }
        }, 100);
    }


    /**
     * uri 转地址
     *
     * @param context
     * @param contentURI
     * @return
     */

    public static String getRealPathFromURI(Context context, Uri contentURI) {
        String result;
        Cursor cursor = context.getContentResolver().query(contentURI,
                new String[]{MediaStore.Images.ImageColumns.DATA},//
                null, null, null);
        if (cursor == null) result = contentURI.getPath();
        else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(index);
            cursor.close();
        }
        return result;
    }
}
